package cn.yl.fxboot.application.action;

import java.io.File;
import java.util.List;
import java.util.Optional;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.yl.fxboot.application.service.Common;
import cn.yl.fxboot.application.service.DecodeVideo;
import cn.yl.fxboot.application.service.DouyinHelper;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;

public class MultiActions {
	/**
	 * 选择源文件
	 * @param node
	 * @return
	 */
	public EventHandler<ActionEvent> multiSrcBtnHandler(TextField node) {
		return new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				FileChooser fileChooser = new FileChooser();
				fileChooser.setTitle("选择导入文件");
				// dirChooser.setInitialDirectory(new File("D:\\Documents"));
				File dir = fileChooser.showOpenDialog(node.getScene().getWindow());
				if (dir != null && dir.exists() && dir.isFile()) {
					String filename = dir.getPath();
					if(filename.endsWith(".txt")) {
						node.setText(filename);
					}else {
						Alert alert = new Alert(AlertType.ERROR);
						alert.setContentText("请选择.txt格式的文本文档");
						alert.setHeaderText("");
						alert.show();
					}
				}else {
					Alert alert = new Alert(AlertType.ERROR);
					alert.setContentText("请选择.txt格式的文本文档");
					alert.setHeaderText("");
					alert.show();
				}
			}
		};
	}
	
	public EventHandler<ActionEvent> multiAddrBtnHandler(TextField node) {
		return new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				DirectoryChooser dirChooser = new DirectoryChooser();
				dirChooser.setTitle("选择导出文件夹");
				// dirChooser.setInitialDirectory(new File("D:\\Documents"));
				File dir = dirChooser.showDialog(node.getScene().getWindow());
				if (dir != null) {
					node.setText(dir.getPath());
				}
			}
		};
	}
	
	/**
	 * 开始下载
	 * @param multiSrc_TF
	 * @param multiAddr_TF
	 * @return
	 */
	public EventHandler<ActionEvent> multiDownloadHandler(TextField multiSrc_TF, TextField multiAddr_TF) {
		return new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				Task<Void> dlTask = new Task<Void>() {
					@Override
					protected Void call() throws Exception {
						String filePath = multiSrc_TF.getText();
						String output = multiAddr_TF.getText();
						updateMessage("读取文件:"+filePath);
						String content = FileUtil.readString(filePath, "UTF-8");
						List<String> list = ReUtil.findAllGroup0(Common.RE_URLS, content);
						updateMessage("解析到"+list.size()+"条链接");
						for(int i=0; i<list.size();i++) {
							int j=i+1;
							try {
								Optional<DecodeVideo> videoOpt = DouyinHelper.decode(list.get(i));
								if (videoOpt.isPresent()) {
									DecodeVideo video = videoOpt.get();
									updateMessage("视频获取成功..正在下载第"+j+"个视频...");
									CheckBox cb = (CheckBox) multiAddr_TF.getScene().lookup("#multiOnlyVideo");
									String dir = "";
									if(cb.isSelected()) {
										dir = DouyinHelper.downloadOnlyVideo(video, output);
									}else {
										dir = DouyinHelper.download(video, output);
									}
									updateMessage("第"+j+"个视频下载完成,任务结束,文件位置: " + dir);
								} else {
									updateMessage("error:没有对应的视频");
								}

							} catch (Exception e) {
								updateMessage("error:第"+j+"个视频下载失败,请求链接错误");
								e.printStackTrace();
							}
						}
						return null;
					}
					
					@Override
					protected void running() {
						updateMessage("开始!");
					}

					@Override
					protected void succeeded() {
						updateMessage("结束!");
					}

					@Override
					protected void cancelled() {
						updateMessage("被中断!");
					}

					@Override
					protected void failed() {
						updateMessage("error:失败!");
					}
					
				};
				
				String taskId = "任务 " + RandomUtil.randomString(4)+" --> " ;
				dlTask.messageProperty().addListener(new ChangeListener<String>() {
					@Override
					public void changed(ObservableValue<? extends String> observable, String oldValue,
							String newValue) {
						MsgPaneActions.doLog(taskId + newValue);
					}
				});
				new Thread(dlTask).start();
			}
		};
	}
	
}
